package robot;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class DesktopUtil {
    static GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    static GraphicsDevice[] gds = ge.getScreenDevices();

    public static BufferedImage getScreenPicture(GraphicsDevice graphicsDevice) {
        Rectangle screenRect = graphicsDevice.getDefaultConfiguration().getBounds();
        BufferedImage bi = getGraphicsDeviceRobot(graphicsDevice).createScreenCapture(screenRect);
        return bi;
    }

    public static Robot getGraphicsDeviceRobot(GraphicsDevice graphicsDevice) {
        Robot rb = null; //在此用来抓取屏幕，即截屏。详细可见API
        try {
            rb = new Robot(graphicsDevice);
        } catch (AWTException e) {
            System.out.println("获取当前显示设备robot失败");
            e.printStackTrace();
            return rb;
        }
        return rb;
    }

    public static void writeImg(BufferedImage bi, String path) {
        //保存图片
        File outputfile = new File(path);
        try {
            boolean writeDown = ImageIO.write(bi, "png", outputfile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static BufferedImage getImg() {
        long startTime = System.currentTimeMillis();   //获取开始时间
        BufferedImage bi = DesktopUtil.getScreenPicture(DesktopUtil.gds[0]);
        long endTime = System.currentTimeMillis(); //获取结束时间
        //System.out.println("程序运行时间： " + (endTime - startTime) + "ms");
        return bi;
    }
}
